package com.mical.demo.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api")
public class SecureController {

    @PostMapping("/user")
    public ResponseEntity<?> getUserInfo(Authentication authentication) {
        // 方式1：通过方法参数注入（推荐）
        if (authentication == null) {
            return ResponseEntity.status(401).body("未认证");
        }

        // 方式2：通过SecurityContext获取
        Authentication auth2 = SecurityContextHolder.getContext().getAuthentication();

        return ResponseEntity.ok(Map.of(
                "name", authentication.getName(),
                "roles", authentication.getAuthorities()
        ));
    }
}